package com.fy.fyai.controller;

import com.fy.fyai.service.downloaddecorator.component.FileInfo;
import com.fy.fyai.service.downloaddecorator.enums.UserTypeEnum;
import com.fy.fyai.service.downloaddecorator.factory.DownloadDecoratorFactory;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;

/**
 * @author fwq
 * @description COS下载限流控制器
 * @date 2025-11-03 16:10
 */
@Slf4j
@RestController
@RequestMapping("/cos")
@Tag(name = "COS下载限流控制器")
public class CosController {

    @Resource
    private DownloadDecoratorFactory downloadDecoratorFactory;

    /**
     * 下载文件（流式响应，支持限流）
     *
     * @param fileId 文件ID
     * @param userType 用户类型（NORMAL/VIP/SVIP，默认NORMAL）
     * @return 文件流响应
     */
    @Operation(summary = "下载文件（流式响应，支持限流）")
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(
            @RequestParam("fileId") String fileId,
            @RequestParam(value = "userType", required = false, defaultValue = "NORMAL") String userType) {
        
        try {
            // 1. 根据用户类型获取对应的下载组件（可能包含装饰器链）
            UserTypeEnum userTypeEnum = UserTypeEnum.getByCode(userType.toLowerCase());
            if (userTypeEnum == null) {
                userTypeEnum = UserTypeEnum.NORMAL;
            }
            
            log.info("下载文件：fileId={}, userType={}", fileId, userTypeEnum);
            
            // 2. 获取文件信息（包含限流处理后的输入流）
            FileInfo fileInfo = downloadDecoratorFactory.createDownloadComponent(userTypeEnum)
                    .downloadFile(fileId);
            
            // 3. 构建流式响应
            InputStream inputStream = fileInfo.getInputStream();
            Resource resource = new InputStreamResource(inputStream) {
                @Override
                public long contentLength() {
                    return fileInfo.getFileSize();
                }
            };
            
            // 4. 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(fileInfo.getContentType()));
            headers.setContentLength(fileInfo.getFileSize());
            headers.setContentDispositionFormData("attachment", fileInfo.getFileName());
            
            log.info("文件下载响应准备完成：fileName={}, fileSize={}", fileInfo.getFileName(), fileInfo.getFileSize());
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
                    
        } catch (Exception e) {
            log.error("文件下载失败：fileId={}", fileId, e);
            return ResponseEntity.internalServerError().build();
        }
    }
}
